import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _counter = 1;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'InheritedWidget',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        splashColor: Colors.transparent,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('InheritedWidget'),
        ),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            setState(() {
              _counter++;
            });
          },
        ),
        body: HomePage(_counter),
      ),
    );
  }
}

// 使用InheritedWidget共享数据，管理状态
// 之前想要给Demo1Widget、Demo2Widget共享数据可以通过构造方法传入，但是这两个Widget里面还有各自节点
// 参数多次传递很麻烦
class HomePage extends StatelessWidget {
  int _counter;

  HomePage(this._counter);

  @override
  Widget build(BuildContext context) {
    return CounterWidget(
      counter: _counter,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Demo1Widget(),
            Demo2Widget(),
          ],
        ),
      ),
    );
  }
}

class Demo1Widget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    int _counter = CounterWidget.of(context).counter;
    return Container(
      color: Colors.red,
      child: Text("当前计数 $_counter"),
    );
  }
}

class Demo2Widget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    int _counter = CounterWidget.of(context).counter;
    return Container(
      color: Colors.blue,
      child: Text("当前计数 $_counter"),
    );
  }
}

// 全局状态管理 InheritedWidget：跨组件数据传递
// 将数据放入InheritedWidget中
class CounterWidget extends InheritedWidget {
  // 定义需要共享的数据
  final int counter;

  CounterWidget({this.counter, Widget child}) : super(child: child);

  // 声明静态方法获取该widget实例，以便外界获取共享数据数据，of名称为自定义
  // 当外界widget传入content参数时，该content即element，会沿着Element树，
  // 找到最近的CounterElement，从Element中取出Widget对象，从而获取共享数据
  static CounterWidget of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType();
  }

  // true：执行依赖当前InheritedWidget的State中的didChangeDependencies方法，false不执行
  @override
  bool updateShouldNotify(CounterWidget oldWidget) {
    return oldWidget.counter != counter;
  }
}
